﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DevelopTool.Bll.NoteBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Model.NoteModels;
using Sunny.UI;
using static Sunny.UI.UIImageListBox;

namespace DevelopTool.Forms.NoteForms
{
    /// <summary>
    /// 笔记窗体
    /// </summary>
    public partial class NoteForm : BaseUIPage
    {
        /// <summary>
        /// 笔记操作类
        /// </summary>
        private NoteBll noteBll;

        /// <summary>
        /// 笔记附件操作类
        /// </summary>
        private NoteFileBll noteFileBll;


        /// <summary>
        /// 笔记对象
        /// </summary>
        private Note note;


        public NoteForm(Note note)
        {
            InitializeComponent();

            this.note = note;

            noteBll = new NoteBll();
            noteFileBll = new NoteFileBll();
        }


        private void NoteForm_Load(object sender,EventArgs e)
        {
            this.codeEditorControl.ContentText = note.Text;
            this.codeEditorControl.ContentType = string.IsNullOrEmpty(note.TextType) ? "Text" : note.TextType;
            this.codeEditorControl.PanelTitle = note.NodeName;

            //显示文件列表
            LoadListBoxFile(noteFileBll.GetList(note.Id),true);
        }


        /// <summary>
        /// 编辑器文本改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void codeEditorControl_ContentTextChanged(object sender,EventArgs e)
        {
            SaveNote();
        }

        /// <summary>
        /// 保存笔记事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiSymbolButtonSaveNote_Click(object sender,EventArgs e)
        {
            SaveNote();
            this.ShowSuccessNotifier("笔记保存成功");
        }


        /// <summary>
        /// 保存笔记
        /// </summary>
        private void SaveNote()
        {
            this.note.Text = this.codeEditorControl.ContentText;
            this.note.TextType = this.codeEditorControl.TextEditorControl.Document.HighlightingStrategy.Name;

            this.note= noteBll.Save(this.note);
        }


        #region 笔记附件操作


        /// <summary>
        /// 添加附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiSymbolButtonAddFile_Click(object sender,EventArgs e)
        {
            using(OpenFileDialog dialog = new OpenFileDialog { Title = "选择笔记附件" })
            {
                dialog.Multiselect = true;//允许文件多选
                if(dialog.ShowDialog() == DialogResult.OK)
                {
                    var fileNames = dialog.FileNames;
                    List<NoteFile> noteFileList = fileNames.Select(it => new NoteFile()
                    {
                        FilePath = it,
                    }).ToList();
                    LoadingHelper.ShowLoading($"压缩并上传文件",() =>
                    {
                        noteFileList = noteFileBll.UploadFiles(note.Id,noteFileList);
                    });

                    LoadListBoxFile(noteFileList);
                }
            }
        }

        /// <summary>
        /// 加载ListBox文件列表
        /// </summary>
        /// <param name="noteFileList"></param>
        private void LoadListBoxFile(List<NoteFile> noteFileList,bool reload = false)
        {
            uiSplitContainer2.Panel2Collapsed = noteFileList.Count <= 0;

            if(reload) uiListBoxFile.Items.Clear();
            foreach(NoteFile noteFile in noteFileList)
            {
                var bitmap = IconHelper.GetFileIcon(noteFile.Filename,false).ToBitmap();//根据文件名获取文件图标
                bitmap.Tag = noteFile;

                uiListBoxFile.AddImage(new ImageListItem(bitmap,noteFile.Filename));
            }
        }



        private void 删除文件ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            if(uiListBoxFile.SelectedItem == null) return;
            var noteFile = uiListBoxFile.SelectedItem.Image.Tag as NoteFile;
            if(this.ShowAskDialog($"{GlobalData.AppName_zh}-重要提示", $"是否确定删除附件【{noteFile.Filename}】，删除后无法恢复！", UIStyle.Orange))
            {
                LoadingHelper.ShowLoading("删除文件",() =>
                {
                    noteFileBll.Delete(noteFile.Id);
                });

                this.ShowSuccessNotifier($"{noteFile.Filename}已删除");
                LoadListBoxFile(noteFileBll.GetList(noteFile.NoteId),true);
            }
        }

        /// <summary>
        /// 文件列表右键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiListBoxFile_MouseDown(object sender,MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right && uiListBoxFile.SelectedItem != null)
            {
                uiListBoxFile.ContextMenuStrip = ContextMenuStripFile;
            }
        }

        private void 打开文件ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            if(uiListBoxFile.SelectedItem == null) return;
            if(uiListBoxFile.SelectedItem.Image.Tag is NoteFile noteFile)
            {
                string filePath = Path.Combine(GlobalData.AppTempDirectory,noteFile.Filename);//文件路径
                LoadingHelper.ShowLoading("打开文件",() =>
                {
                    noteFileBll.SaveAs(noteFile.Id,filePath);//将文件保存到临时目录
                    System.Diagnostics.Process.Start(filePath);//用系统自带的默认程序打开文件
                });
            }
        }


        /// <summary>
        /// 选中文件列表中的某一项事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiListBoxFile_SelectedValueChanged(object sender,EventArgs e)
        {
            if(uiListBoxFile.SelectedIndex < 0) return;

            //获取关联的笔记附件列表
            var noteFiles = noteFileBll.GetList(note.Id);
            var noteFile = noteFiles[uiListBoxFile.SelectedIndex];

            UIImageListBox item = sender as UIImageListBox;
            if(item.SelectedItem.Description != noteFile.Filename)
            {
                return;
            }
            item.SelectedItem.Image.Tag = noteFile;//绑定指定的附件对象


            //设置tips
            string tipStr = $"原始文件大小：{StorageHelper.FormatBytes(noteFile.OriginalLength)}\n";
            tipStr += $"压缩文件大小：{StorageHelper.FormatBytes(noteFile.CompressLength)}\n";
            tipStr += $"上传时间：{noteFile.CreateTime}\n";

            uiToolTip1.SetToolTip(item,tipStr,
                noteFile.Filename,61530,25,UIColor.White);
            uiToolTip1.Tag = item;
        }

        /// <summary>
        /// 鼠标移出控件时，删除tips
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiListBoxFile_MouseMove(object sender,MouseEventArgs e)
        {
            if(uiToolTip1.Tag != null)
            {
                uiToolTip1.RemoveToolTip((UIImageListBox)uiToolTip1.Tag);
            }
        }

        private void 文件另存为ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            if(uiListBoxFile.SelectedItem == null) return;
            if(uiListBoxFile.SelectedItem.Image.Tag is NoteFile noteFile)
            {
                string fileName = noteFile.Filename;
                if(Dialogs.SaveFileDialog(ref fileName))
                {
                    LoadingHelper.ShowLoading("保存文件",() =>
                    {
                        noteFileBll.SaveAs(noteFile.Id,fileName);//将文件保存到选择的路径
                    });

                    this.ShowSuccessNotifier($"【{Path.GetFileName(fileName)}】保存成功");
                }
            }
        }

        #endregion

        
    }
}
